package map.android.baidu.carpool.page.pay;

import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.baidu.components.api.extra.APIProxy;
import com.baidu.lbs.net.http.model.ComNetData;
import com.baidu.lbs.net.http.model.IDataStatusChangedListener;
import com.baidu.mapframework.api.ComAPIManager;
import com.baidu.mapframework.widget.MToast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.data.impl.CreateCommentData;
import map.android.baidu.carpool.page.CarpoolBasePage;
import map.android.baidu.carpool.preferences.CarpoolSharedPreferences;
import map.android.baidu.carpool.response.CreateCommentResponse;
import map.android.baidu.carpool.response.MainConfigResponse;
import map.android.baidu.carpool.response.OrderDetailResponse;
import map.android.baidu.carpool.utils.CarpoolAlertDialog;
import map.android.baidu.carpool.utils.StatisticsUtil;
import map.android.baidu.carpool.utils.TitleHelpler;
import map.android.baidu.carpool.widget.RoundImageView;

/**
 * Created by zhangtongyu on 15/4/1.
 * 评价车主页面
 */
public class CreateCarerCommentPage extends CarpoolBasePage{
    private static String TAG = "carerComment";

    private Context mContext;
    private Resources mRes;
    private LayoutInflater mInflater;

    private View mView;
    private TitleHelpler mTitleHelper;

    private TextView mDriverNameTv;
    private TextView mDriverInfoTv;
    private TextView mEvaluateNumTv;
    private RatingBar mRatingBar;
    private Button mCommitCommentBt;
    private EditText mContentEt;
    private RoundImageView mDriverHeadIm;

    private ImageLoader mImageLoader;
    private DisplayImageOptions options;

    private Bundle mBundle;

    private CreateCommentResponse mResponse;
    private IDataStatusChangedListener<CreateCommentResponse> listener = new IDataStatusChangedListener<CreateCommentResponse>() {
        @Override
        public void onDataStatusChanged(ComNetData<CreateCommentResponse> data, CreateCommentResponse response, int dataStatus) {
            if (response != null && dataStatus == ComNetData.DATA_STATUS_SUCCESS && response.errNo == 0 && response.data != null) {
                Bundle bundleForCommentSuccess = new Bundle();
                bundleForCommentSuccess.putSerializable(CreateCommentResponse.class.getName(), response);
                APIProxy.navi().navigateTo(CommentSuccessPage.class, bundleForCommentSuccess);
                showLoadingDialog(false);
            } else if (response != null && dataStatus == ComNetData.DATA_STATUS_SUCCESS && response.errNo == 8002) {
                Bundle bundleForCommentSuccess = new Bundle();
                bundleForCommentSuccess.putSerializable(CreateCommentResponse.class.getName(), response);
                APIProxy.navi().navigateTo(CommentSuccessPage.class, bundleForCommentSuccess);
                showLoadingDialog(false);
            } else {
                MToast.show(mContext , "评价失败,请稍后重试");
                showLoadingDialog(false);
        }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        mContext = APIProxy.res().getBaseActivity();
        mRes = APIProxy.res().getResources();
        mInflater = APIProxy.res().getInflater();
        if (mView == null) {
            mBundle = getArguments();
            mView = APIProxy.res().inflate(R.layout.layout_page_create_carer_comment);
            ComAPIManager.getComAPIManager().
                    getResourceAPI(getComId()).getBaseActivity().getWindow().
                    setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            initView();
            initImageLoader();
            initData();
        } else {
            ViewGroup parent = (ViewGroup) mView.getParent();
            if (parent != null) {
                parent.removeView(mView);
            }
        }
        return mView;
    }

    private void initView() {
        mTitleHelper = new TitleHelpler(mView);
        mTitleHelper.setLeftView(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               alertBackDialog();
            }
        });
        mTitleHelper.setCenterView("评价车主");
        mDriverNameTv = (TextView) mView.findViewById(R.id.driver_name);
        mDriverInfoTv = (TextView) mView.findViewById(R.id.driver_info);
        mEvaluateNumTv = (TextView) mView.findViewById(R.id.user_evaluate_num);
        mRatingBar = (RatingBar) mView.findViewById(R.id.car_driver_ratingbar);
        mRatingBar.setRating(0);
        mContentEt = (EditText) mView.findViewById(R.id.et_create_comment);
        mContentEt.setMovementMethod(ScrollingMovementMethod.getInstance());
        mCommitCommentBt = (Button) mView.findViewById(R.id.bt_commit_comment);
        mDriverHeadIm = (RoundImageView) mView.findViewById(R.id.car_driver_circle_image);

        mRatingBar.setIsIndicator(false);

        mCommitCommentBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_CREATE_COMMENT_PAGE, StatisticsUtil.OFFLINE_ACT_COMMIT_COMMENT_BT);
                if((int)Math.ceil(mRatingBar.getRating()) <= 0){
                    MToast.show(mContext, "小主，请为车主评价星级");
                    return;
                }

                if(mContentEt.getText().toString().length() > 140){
                    MToast.show(mContext, "小主，评价内容不能超过140个字");
                    return;
                }
                alertConfirmDialog();
            }
        });
    }

    private void initData() {
        if(mBundle != null){
            if(mBundle.containsKey(OrderDetailResponse.class.getName())){
                OrderDetailResponse response = (OrderDetailResponse) mBundle.get(OrderDetailResponse.class.getName());
                if(response != null && response.data != null) {
                    if(!TextUtils.isEmpty(response.data.carerNickname)) {
                        mDriverNameTv.setText(response.data.carerNickname);
                    }
                    StringBuilder sb = new StringBuilder();
                    if(!TextUtils.isEmpty(response.data.carColor)){
                        sb.append(response.data.carColor + " ");
                    }
                    if(!TextUtils.isEmpty(response.data.carBrand)){
                        sb.append(response.data.carBrand + " ");
                    }
                    if(!TextUtils.isEmpty(response.data.carNumber)){
                        sb.append(response.data.carNumber + " ");
                    }
                    if(!TextUtils.isEmpty(response.data.carType)){
                        String carTypeValue = "";
                        MainConfigResponse mainConfigResponse = CarpoolSharedPreferences.getCacheMainConfigResponse(APIProxy.res().getBaseActivity());
                        if(mainConfigResponse != null && mainConfigResponse.data != null && mainConfigResponse.data.carType != null && mainConfigResponse.data.carType.size() != 0){
                            for(int index = 0; index < mainConfigResponse.data.carType.size(); index++){
                                if(mainConfigResponse.data.carType.get(index) != null){
                                    if(response.data.carType.equals(mainConfigResponse.data.carType.get(index).type)){
                                        carTypeValue = mainConfigResponse.data.carType.get(index).name;
                                    }
                                }
                            }
                        }
                        if(!TextUtils.isEmpty(carTypeValue)) {
                            sb.append("(" + carTypeValue + ")");
                        }
                    }
                    setUserCount(response.data.commentCount);
                    displayImageView(response.data.carerPic, mDriverHeadIm);
                    mDriverInfoTv.setText(sb.toString());
                    mRatingBar.setIsIndicator(false);
                }
            }
        }


    }


    private void alertConfirmDialog(){
        if (mBundle == null) {
            return;
        }
        if(mBundle.containsKey(OrderDetailResponse.class.getName())) {
            final OrderDetailResponse response = (OrderDetailResponse) mBundle.getSerializable(OrderDetailResponse.class.getName());
            if(response != null && response.data != null){
                CarpoolAlertDialog.Builder builder = new CarpoolAlertDialog.Builder(getActivity());
                builder.setTitle("确认提交评价？");
                builder.setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //直接结束dialog
                    }
                });
                builder.setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showLoadingDialog(true);
                        CreateCommentData commentData = new CreateCommentData(mContext);
                        commentData.setDriverId(response.data.carerId);
                        commentData.setOrderId(response.data.orderId);
                        commentData.setScore(String.valueOf((int)Math.ceil(mRatingBar.getRating())));
                        commentData.setContent(mContentEt.getText().toString());
                        commentData.post(listener);
                    }
                });
                builder.create().show();
            }
        }
    }

    private void alertBackDialog(){
        CarpoolAlertDialog.Builder builder = new CarpoolAlertDialog.Builder(getActivity());
        builder.setNegativeButton("继续评价", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //直接结束dialog
            }
        });
        builder.setPositiveButton("取消评价", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBundle.putBoolean("needRefresh", true);
                goBack(mBundle);
            }
        });
        builder.setTitle("返回后您的评价内容将不被保存");
        builder.create().show();
    }

    @Override
    public boolean onBackPressed() {
        alertBackDialog();
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
    }


    /**
     * @param count
     */
    protected void setUserCount(int count) {
        StringBuilder sb = new StringBuilder();
        sb.append("来自");
        sb.append("<font color=\"#ff481d\">");
        sb.append(count);
        sb.append("</font>");
        sb.append("人");
        CharSequence cs = Html.fromHtml(sb.toString());
        mEvaluateNumTv.setText(cs);
    }

    private void initImageLoader() {
        mImageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .cacheInMemory()
                .cacheOnDisc()
                .showImageForEmptyUri(APIProxy.res().getDrawable(R.drawable.car_driver_bg))
                .cacheInMemory().build();
    }

    private void displayImageView(String url, ImageView imageView) {
        String finalUrl = "";
        finalUrl = url;
        mImageLoader.clearDiskCache();
        mImageLoader.displayImage(finalUrl, imageView, options, new SimpleImageLoadingListener());

    }
}
